package com.xulu.romance.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xulu.romance.pojo.QuestionTag;
import com.xulu.romance.service.QuestionTagService;
import com.xulu.romance.constants.Constant;
import com.xulu.romance.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;

/**
 * @version 1.0
 * @Author xiaoxulu
 * @Date 2024/1/13 22:03
 */

@RestController
@CrossOrigin
@RequestMapping("/api/questionTag")
@Api(tags = "问题标签")
@Slf4j
public class QuestionTagController {

    @Autowired
    private QuestionTagService questionTagService;

    @GetMapping("/findAll")
    @ApiOperation("查询所有")
    public R findAll(){
        List<QuestionTag> questionTagList = questionTagService.list();
        return R.ok().put("questionTagList",questionTagList);
    }

    @GetMapping("/front/findAll")
    @ApiOperation("查询所有")
    public R frontFindAll(){
        List<QuestionTag> questionTagList = questionTagService.list();
        return R.ok().put("questionTagList",questionTagList);
    }

    @GetMapping("/findAll/{currentPage}/{size}")
    @ApiOperation("分页查询")
    public R findPage(@PathVariable Long currentPage, @PathVariable Long size, QuestionTag condition) {
        // 创建分页对象
        IPage<QuestionTag> page = new Page<>(currentPage, size);

        // 构建查询条件
        QueryWrapper<QuestionTag> queryWrapper = new QueryWrapper<>();
        if (condition != null) {
            // 如果条件不为空，添加相应的查询条件
            if (StringUtils.isNotBlank(condition.getTagName())) {
                queryWrapper.like("tag_name", condition.getTagName());
            }
        }
        // 根据创建时间降序排序
        queryWrapper.orderByDesc("update_time");

        // 执行分页查询
        IPage<QuestionTag> questionTagIPage = questionTagService.page(page, queryWrapper);

        // 获取查询结果
        List<QuestionTag> questionTagList = questionTagIPage.getRecords();
        long total = questionTagIPage.getTotal();

        // 返回结果
        return Objects.requireNonNull(R.ok().put("questionTagList", questionTagList)).put("count",total);
    }

    @GetMapping("/findById/{id}")
    @ApiOperation("根据id查询")
    public R findById(@PathVariable Integer id){
        QuestionTag questionTag = questionTagService.getById(id);
        return R.ok().put("questionTag",questionTag);
    }




    @PostMapping("/save")
    @ApiOperation("添加问题标签")
    public R save(@RequestBody QuestionTag questionTag){

        try {
            boolean save = questionTagService.save(questionTag);
            if (!save){
                return Objects.requireNonNull(new R().put("code", Constant.FAILURE_CODE)).put("message", Constant.SAVE_FAILURE);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return Objects.requireNonNull(new R().put("code", Constant.SUCCESS_CODE)).put("message", Constant.SAVE_SUCCESS);
    }

    @PostMapping("/update")
    @ApiOperation("更新问题标签")
    public R update(@RequestBody QuestionTag questionTag){
        boolean save = questionTagService.updateById(questionTag);
        if (!save){
            return Objects.requireNonNull(new R().put("code", Constant.FAILURE_CODE)).put("message", Constant.UPDATE_FAILURE);
        }
        return Objects.requireNonNull(new R().put("code", Constant.SUCCESS_CODE)).put("message", Constant.UPDATE_SUCCESS);
    }

    @DeleteMapping("/delete/{id}")
    @ApiOperation("删除问题标签")
    public R delete(@PathVariable Integer id){
        boolean save = questionTagService.removeById(id);
        if (!save){
            return Objects.requireNonNull(new R().put("code", Constant.FAILURE_CODE)).put("message", Constant.DELETE_FAILURE);
        }
        return Objects.requireNonNull(new R().put("code", Constant.SUCCESS_CODE)).put("message", Constant.DELETE_SUCCESS);
    }

    @PostMapping("/deleteBatch")
    @ApiOperation("批量删除问题标签")
    public R deleteBatch(@RequestBody List<Integer> ids){
        boolean save = questionTagService.removeBatchByIds(ids);
        if (!save){
            return Objects.requireNonNull(new R().put("code", Constant.FAILURE_CODE)).put("message", Constant.DELETE_FAILURE);
        }
        return Objects.requireNonNull(new R().put("code", Constant.SUCCESS_CODE)).put("message", Constant.DELETE_SUCCESS);
    }

    @GetMapping("/export")
    @ApiOperation("导出问题标签")
    public void export(HttpServletResponse response) throws Exception {
        List<QuestionTag> list = questionTagService.list();
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.addHeaderAlias("id","id");
        writer.addHeaderAlias("tagName","问题标签");


        writer.setOnlyAlias(true);

        writer.write(list,true);

        // 设置response参数
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        String name = URLEncoder.encode("问题标签", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + name + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out,true);
        out.close();
        writer.close();
    }

    @PostMapping("/import")
    @ApiOperation("导入问题标签")
    public R importUser(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        List<QuestionTag> questionTagList = reader.readAll(QuestionTag.class);
        boolean save = questionTagService.saveBatch(questionTagList);
        if (!save){
            return Objects.requireNonNull(new R().put("code", Constant.FAILURE_CODE)).put("message", Constant.IMPORT_FAILURE);
        }
        return Objects.requireNonNull(new R().put("code", Constant.SUCCESS_CODE)).put("message", Constant.IMPORT_SUCCESS);
    }

}
